package com.yifeng.repo.tookit.oss.web;

import com.gomcarter.frameworks.base.json.ErrorCode;
import com.yifeng.repo.base.utils.converter.JacksonHelper;
import com.yifeng.repo.base.utils.servlet.RequestHelper;
import com.yifeng.repo.base.utils.servlet.ResponseHelper;
import com.yifeng.repo.tookit.oss.OssFileClient;
import com.yifeng.repo.tookit.oss.model.SignatureQuery;
import com.yifeng.repo.tookit.oss.model.SignatureResult;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by daibing on 2024/12/04.
 */
@Slf4j
public class OssServlet extends HttpServlet {
    public static final String APPLY = "/apply";
    private final OssFileClient ossFileClient;

    public OssServlet(OssFileClient ossFileClient) {
        this.ossFileClient = ossFileClient;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        try {
            if (uri.endsWith(APPLY)) {
                String appId = req.getParameter("appId");
                String path = req.getParameter("path");
                SignatureResult signatureResult = ossFileClient.apply(new SignatureQuery(appId, path));
                ResponseHelper.doWrite(resp, JacksonHelper.toJson(signatureResult.getSignature()));
                return;
            }
            ResponseHelper.doError(resp, ErrorCode.noPermission.getCode(),
                    "http.method_post_not_supported from " + RequestHelper.getRemoteAddress(req));
        } catch (Throwable t) {
            log.error("oss doPost error: ", t);
            ResponseHelper.doError(resp, ErrorCode.systemInternalError.getCode(), t.getMessage());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

}
